<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Post\BatchRestore;
use App\Admin\Actions\Post\GoodsListSmall;
use App\Admin\Actions\Post\Restore;
use App\Admin\Forms\GoodsList;
use App\Admin\Repositories\SeckillGood;
use App\Models\Good;
use App\Models\GoodsConfig;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Show;
use Illuminate\Support\Facades\Redis;

class SeckillGoodController extends AdminController
{

    //连接redis
    public $redis;

    public function __construct()
    {
        $this->redis = new \Redis();
        $this->redis->connect('127.0.0.1', 6379);
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new SeckillGood(), function (Grid $grid) {
            $grid->column('id', '序号')->sortable();
            //列表传值
            $grid->column('goods_id', '商品')->display('查看')->modal(function ($modal) {
                $goodsId = $this->goods_id;
                return GoodsList::make(['goods_id' => $goodsId]);
            });
            //表单传值
            //$grid->user->display('View')->modal(function (Grid\Displayers\Modal $modal) {
            //	return UserProfile::make()->payload(['type' => 123456789]);
            //});
            $grid->column('seckill_image', '图片')->image(100, 100);
            $grid->column('seckill_count', '秒杀数量');
            $grid->column('seckill_price', '秒杀价');
            $grid->column('seckill_state')->display(function ($e) {
                return $e == 1 ? true : false;
            })->switch('123', true);

            $grid->column('seckill_title');
            $grid->column('seckill_synopsis', '商品简介');
            $grid->column('start_time');


            ////页面显示别的模型
            //$grid->column('nickName')->display(function ($e) {
            //	return (new UserInfo())->where('id', 1)->first('nickName')->toArray();
            //});


            //回收站
            $grid->filter(function ($filter) {
                // 范围过滤器，调用模型的`onlyTrashed`方法，查询出被软删除的数据。
                $filter->scope('trashed', '回收站')->onlyTrashed();
            });
            //恢复
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                if (request('_scope_') == 'trashed') {
                    $actions->append(new Restore(\App\Models\SeckillGood::class));
                }
            });
            //批量恢复
            $grid->batchActions(function (Grid\Tools\BatchActions $batch) {
                if (request('_scope_') == 'trashed') {
                    $batch->add(new BatchRestore(\App\Models\SeckillGood::class));
                }
            });
            //搜索
            $grid->filter(function ($filter) {
                // 展开过滤器
                // 在这里添加字段过滤器
                $filter->like('seckill_title', '标题');
            });
            //查询状态
            $grid->selector(function (Grid\Tools\Selector $selector) {
                $selector->select('seckill_state', '状态', [
                    1 => '开启',
                    0 => '关闭',
                ]);
            });
            //下拉框查询状态
            //$grid->quickCreate(function (Grid\Tools\QuickCreate $create) {
            //	$create->select('seckill_state')->options([
            //		1 => '阿萨大',
            //		0 => 'asd',
            //	]);
            //});
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new SeckillGood(), function (Show $show) {
            $show->field('id');
            $show->field('goods_id');
            $show->field('seckill_count');
            $show->field('start_time');
            $show->field('time_slot', '时间段');
            $show->field('seckill_price');;
            $show->field('seckill_state');
            $show->field('seckill_title');
            $show->field('seckill_image');
            $show->field('seckill_synopsis');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new SeckillGood(), function (Form $form) {
            $form->display('id');

            $form->selectTable('goods_id')->from(GoodsListSmall::make())->saving(function ($e) {
                return $e;
                //验证一件商品只能秒杀一次
            });

            $form->number('seckill_count', '秒杀总数量')->required();
            $form->date('start_time', '开始时间（天）')->required();
            $form->select('time_slot', '时间段')->options(function ($option) {
                $time = GoodsConfig::get()->toArray();
                $timeArray = [];
                foreach ($time as $value) {
                    $timeArray[$value['id']] = '开始时间' . $value['start_time'] . '点，持续' . $value['continued_time'] . '小时';
                }
                //dd($timeArray);
                return $timeArray;
            })->required();
            $form->number('seckill_price', '秒杀价')->required()->type('number');
            $form->radio('seckill_state')->required()->options(['1' => '开启', '0' => '不开启'])->default('0');
            $form->text('seckill_title')->required();
            $form->text('seckill_synopsis', '商品简介')->required();
            $form->image('seckill_image')->required()->uniqueName()->saveFullUrl();
            $form->display('created_at');
            $form->display('updated_at');
            //状态开启不能删除
            $form->deleting(function (Form $form) {
                $data = $form->model();
                if ($data[0]['seckill_state'] == 1) {
                    return $form->response()->error('已开启不能删除');
                }
                return 0;
            });
            //验证数量和价格
            $form->saving(function (Form $form) {
                // 判断是否是新增操作
                if ($form->isCreating()) {
                    $con = (new Good())->where('id', $form->goods_id)->get()->toArray();
                    $number = $con[0]['goods_amount'];
                    $price = $con[0]['goods_price'];
                    //判断库存
                    if ($form->seckill_count > $con[0]['goods_amount']) {
                        return $form->response()->error("库存不足,目前库存仅剩 $number 件");
                    }
                    //判断价格
                    if ($form->seckill_price > $con[0]['goods_price']) {
                        return $form->response()->error("不能超过原价格,原价格为 $price 元");
                    }
                    $sameDay = date('Y-m-d');
                    //判断时间是否是当天,如果是当天就必须开启
                    if ($form->start_time == $sameDay) {
                        if ($form->seckill_state == 0) {
                            return $form->response()->error("当天时间,商品状态必须开启");
                        }
                    }
                    //判断商品是否热卖
                    $res = \App\Models\SeckillGood::where('start_time', $form->start_time)->where('goods_id', $form->goods_id)->first();
                    if ($res) {
                        return $form->response()->error("当天该商品已经在秒杀中");
                    }
                }
                return 0;
            });

            //保存后判断是否是当天，开始预热
            $form->saved(function (Form $form, $result) {
                //存结束时间
                //查询出时段表
                $time = (new GoodsConfig())->where('id', $form->time_slot)->first();
                //结束时间
                $end_time = $form->start_time . ' ' . intval($time['start_time'] + $time['continued_time']) . ':' . '00' . ':' . '00';
                //开始时间
                $start_time = $form->start_time . ' ' . intval($time['start_time']) . ':' . '00' . ':' . '00';
                //dd($form->start_time, $start_time, $end_time);
                (new \App\Models\SeckillGood())->where('id', $form->getKey())->update(['end_time' => $end_time]);
                //判断添加的商品是否是开启的
                //如果是开启判断是否是当天的,如果是当天就开始预热
                //当天时间

                $sameDay = date('Y-m-d');
                if ($form->seckill_state == '1') {
                    if ($form->start_time == $sameDay) {

                        //开始预热
                        for ($i = 0; $i < $form->seckill_count; $i++) {
                            Redis::lpush('number_' . $form->goods_id, 1);
                        }
                        //根据结束时间-当前时间设置为过期时间，缓存消失则活动结束
                        Redis::set('start_time_' . $form->goods_id, strtotime($start_time), strtotime($form->end_time) - time());
                    }
                }
                return 0;
            });
        });
    }
}


